/* eslint-disable react/sort-comp */
import { messages } from "share/common";
import React, { Component } from "react";
import { Form, Button, Spin, Affix, Checkbox, Input, Row, Icon, Col } from "antd";
import AirCardForm from "../components/air-card-form";
import SupportSuppliers from "../components/support-suppliers-group";
import AirLineServer from "../airline-server";
import { message } from "antd/lib/index";
import "styles/supplier-management/airline-config/platform-common.scss";
import Condition from "components/condition";

const { If } = Condition;

const FormItem = Form.Item;

@Form.create()
class SetAirSupplier extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      airData: [], // 酒店供应商数据列表
      emails: [""], // 邮箱
      bodyData: {},
      supportSuppliers: [],
    };
  }

  componentWillMount() {
    this.initData();
  }

  initData = () => {
    const { getAddedSupplierSigns, getSupportSuppliers } = AirLineServer(this);
    const getAddedSupplierSignsPromise = getAddedSupplierSigns({
      companyOid: this.props.companyOID,
      complete: true,
    }).then((res) => {
      if (res.data.body) {
        this.setState({
          airData: res.data.body || [],
        });
      } else {
        // 增加提示
        message.error(res.data.message);
      }
    });

    const getSupportSuppliersPromise = getSupportSuppliers().then((res) => {
      if (res.data.body) {
        this.setState({
          supportSuppliers: res.data.body,
        });
      } else if (res.data.message) {
        message.error(res.data.message);
      }
    });
    this.setState({ loading: true });
    Promise.all([getAddedSupplierSignsPromise, getSupportSuppliersPromise]).then(() => {
      this.setState({ loading: false });
    });
  };

  onSaveSetting = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { bodyData } = this.state;
        const params = {
          companyOid: this.props.companyOID,
          companyName: this.props.companyName,
          serviceEmail: bodyData.serviceEmail,
          enabledEmail: values.enabledEmail,
          supplierSigns: [],
        };
        // let emails = [];
        // for(let key in values){
        //   if(key.includes('emails')){
        //     emails.push(values[key]);
        //   }
        // }
        // if(values.enabledEmail){
        //   params.serviceEmail = emails.join(',');
        // }
        for (const key in values) {
          if (key.includes("supplier")) {
            const item = Object.assign({}, values[key]);
            item.account = item.account === null ? "{}" : JSON.stringify(item.account);
            params.supplierSigns.push(item);
          }
        }
        AirLineServer(this)
          .saveAirSupplierData(params)
          .then((res) => {
            if (res.data.success) {
              this.initData();
              message.success(messages("supplier-1.key355") /* 保存成功*/);
            } else {
              message.error(res.data.message);
            }
          });
      }
    });
  };

  // onAddEmail = (index) => {
  //   const {emails} = this.state;
  //   if(index === 0){
  //     emails.push('');
  //   }else{
  //     emails.splice(index,1);
  //   }
  //   this.setState({emails});
  // }

  addSupplier = (value) => {
    const airData = this.state.airData;
    const newAirData = { ...value };
    newAirData.account = JSON.parse(newAirData.accountTemplate);
    newAirData.expand = true;
    delete newAirData.accountTemplate;
    if (airData.findIndex((item) => item.supplierCode === newAirData.supplierCode) === -1) {
      newAirData.isEnabled = false;
      newAirData.enableDomestic = false;
      newAirData.enableInternationalRfp = false;
      airData.push(newAirData);
      this.setState({ airData });
    }
  };

  render() {
    const { airData, loading, emails, bodyData, supportSuppliers } = this.state;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const spanNum2 = 12;
    const formLayout = { width: "90%", display: "inline-block" };
    return (
      <div className="airline-config-container airline-suppliers">
        <Spin className="spin" spinning={loading}>
          <h2>{messages("supplier-1.key745") /*已添加服务商*/}</h2>
          <a className="a-line-bottom">
            {
              messages(
                "supplier-1.key746"
              ) /*请仔细检查服务商配置参数，以免造成不必要的问题。请注意点击下方的【保存配置】按钮，及时保存配置*/
            }
          </a>
          <Form>
            {/* 影响初始化，留个hash给你*/}
            {airData.map((item, index) => (
              <FormItem>
                {getFieldDecorator(`supplier${index}`, {
                  initialValue: item,
                })(<AirCardForm expand={item.expand} />)}
              </FormItem>
            ))}
          </Form>
          <br />
          <br />
          <br />
          <h2>{messages("supplier-1.key747") /*汇联易合作服务商*/}</h2>
          <SupportSuppliers supportSuppliers={supportSuppliers} onAdd={this.addSupplier} />
          <br />
          <br />
          <br />
          <br />
          <br />
        </Spin>
        <Affix offsetBottom={0} className="setting-fotter-class">
          <Button style={{ marginLeft: 20 }} type="primary" onClick={this.onSaveSetting}>
            {messages("supplier-1.key356") /* 保存配置*/}
          </Button>
        </Affix>
      </div>
    );
  }
}

export default SetAirSupplier;
